<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ isEdit?'试题修改' :'试题录入' }}</span>
        </div>
        <!-- 表单 -->
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="form.subjectID"
              placeholder="请选择"
              class="selectWidth"
              @change="subjectChangeFn"
            >
              <el-option
                v-for="obj in applyLists.subjectList"
                :key="obj.value"
                :label="obj.label"
                :value="obj.value"
              />
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              v-model="form.catalogID"
              placeholder="请选择"
              class="selectWidth"
            >
              <el-option
                v-for="obj in applyLists.directoryList"
                :key="obj.value"
                :label="obj.label"
                :value="obj.value"
              />
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              v-model="form.enterpriseID"
              placeholder="请选择"
              class="selectWidth"
            >
              <el-option
                v-for="obj in applyLists.firmList"
                :key="obj.id"
                :label="obj.company"
                :value="obj.id"
              />
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市：" prop="province">
            <el-col :span="3" class="cityCol">
              <el-select
                v-model="form.province"
                placeholder="请选择"
                @change="provinceChangeFn"
              >
                <el-option
                  v-for="(item, index) in applyLists.provincesList"
                  :key="index"
                  :value="item"
                />
              </el-select>

            </el-col>
          </el-form-item>
          <!-- 地区 -->
          <el-form-item prop="city" class="itemCity">
            <el-col :span="3">
              <el-select v-model="form.city" placeholder="请选择" class="citySelect">
                <el-option
                  v-for="(item, index) in applyLists.citysList"
                  :key="index"
                  :value="item"
                />
              </el-select>
            </el-col>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select
              v-model="form.direction"
              placeholder="请选择"
              class="selectWidth"
            >
              <el-option
                v-for="(item, index) in applyLists.directionList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：">
            <el-radio-group v-model="form.questionType" @change="tabQuestionsTypeFn">
              <el-radio
                v-for="obj in applyLists.questionTypeList"
                :key="obj.value"
                :label="obj.value"
              >
                {{ obj.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：">
            <el-radio-group v-model="form.difficulty">
              <el-radio
                v-for="obj in applyLists.difficultyList"
                :key="obj.value"
                :label="obj.value"
              >
                {{ obj.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干：" prop="question">
            <editor-template ref="wangeditor" v-model="form.question" />
          </el-form-item>
          <!-- 选项 -->
          <el-form-item v-if="form.questionType !== 3" label="选项：">
            <!-- 单选 -->
            <el-radio-group v-if="form.questionType === 1" v-model="radioNum">
              <el-row v-for="(obj, index) in options" :key="index" class="porCol">
                <el-col :span="24">
                  <el-radio :label="index">
                    {{ obj.code }}：<el-input v-model="obj.title" />
                  </el-radio>
                  <image-upload :image-url-edit="obj.img" class="uploadImg" @imageUploadEvent="imageUploadFn($event,index)" />
                </el-col>
              </el-row>
            </el-radio-group>
            <!-- 多选 -->
            <el-checkbox-group
              v-if="form.questionType === 2"
              v-model="checkboxNum"
            >
              <el-row v-for="(obj, index) in options" :key="index" class="porCol">
                <el-col :span="24">
                  <el-checkbox :label="index">
                    {{ obj.code }} ：<el-input v-model="obj.title" /> </el-checkbox>
                  <image-upload class="uploadImg" :image-url-edit="obj.img" @imageUploadEvent="imageUploadFn($event,index)" />
                </el-col>
              </el-row>
            </el-checkbox-group>
          </el-form-item>

          <!-- 增加选项按钮 -->
          <el-form-item>
            <el-button
              v-if="form.questionType !== 3"
              type="danger"
              :disabled="form.questionType === 1"
              size="small"
              @click="addTabAnswerFn"
            >+增加选项与答案</el-button>
          </el-form-item>

          <!-- 解析视频 -->
          <el-form-item label="解析视频：">
            <el-input v-model="form.videoURL" class="InputWidth" />
          </el-form-item>

          <!-- 答案解析 -->
          <el-form-item label="答案解析：" prop="answer">
            <editor-template ref="wangeditoranswer" v-model="form.answer" />
          </el-form-item>

          <!-- 题目备注-->
          <el-form-item label="题目备注：">
            <el-input
              v-model="form.remarks"
              type="textarea"
              :rows="4"
              class="InputWidth"
            />
          </el-form-item>

          <!-- 试题标签 -->
          <el-form-item label="试题标签：">
            <el-select
              v-model="form.tags"
              placeholder="请选择试题标签"
              class="selectWidth"
              multiple
              filterable
              allow-create
              default-first-option
            >
              <el-option
                v-for="obj in applyLists.tagsList"
                :key="obj.value"
                :label="obj.label"
                :value="obj.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button :type="isEdit? 'success':'primary'" @click="addSunmitFn">{{ isEdit? '确认修改':'确认提交' }} </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { list as firm } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as subjectListSimple } from '@/api/hmmm/subjects'
import { simple as directoryListSimple } from '@/api/hmmm/directorys'
import { simple as tagsListSimple } from '@/api/hmmm/tags'
import imageUpload from './Dcomponents/imageUpload.vue'
import { add as addQuestionsNew, detail, update } from '@/api/hmmm/questions'
export default {
  name: 'QuestionsNew',
  components: { imageUpload },
  data() {
    return {
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: '', // 题干 firstEtior
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      options: [],
      radioNum: '', // 单选正确答案的索引号
      checkboxNum: [], // 多选正确答案的索引号
      applyLists: {
        directionList: direction, // 方向列表
        provincesList: provinces(), // 城市列表
        citysList: [], // 地区列表
        firmList: [], // 企业列表
        subjectList: [], // 学科列表
        directoryList: [], // 目录列表
        questionTypeList: questionType, // 题型
        difficultyList: difficulty, // 困难列表
        tagsList: [] // 标签列表
      },
      numBerTotal: 4, // 字母自定义循环四次
      numBerIndex: 0, // 字母自定义循环第几次
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'change' }]
      },
      isEdit: false,
      isEditInfo: {}
    }
  },
  watch: {
    // 监听如果是单选 对option操作
    radioNum: function() {
      if (this.radioNum === '') return
      this.options.forEach((obj) => {
        obj.isRight = false
      })
      this.options[this.radioNum].isRight = true
    },
    // 监听如果是多选 对option操作
    checkboxNum: function() {
      this.options.forEach((obj) => {
        obj.isRight = false
      })
      this.checkboxNum.forEach((item) => {
        this.options[item].isRight = true
      })
    },
    // 监听单选多选切换 对option清空操作
    'form.questionType': function() {
      if (this.isEdit) return
      this.radioNum = ''
      this.checkboxNum = []
      this.options = []
      this.numBerTotal = 4
      this.numBerIndex = 0
      this.letterAdd()
    }
  },
  created() {
    // 调用企业列表方法
    this.applyListsFn()

    // 调用字母增减方法
    this.letterAdd()

    // 调用是否编辑的方法
    this.isEditFn()
    // console.log(this.$route.query.id)
  },
  methods: {
    // 根据options里的code的字母来改变options里的顺序
    getOptionsSubsequence(Array) {
      const newArr = []

      const codeArr = Array.map(obj => obj.code).sort()

      codeArr.forEach(item => {
        const obj = Array.find(obj => obj.code === item)
        newArr.push(obj)
      })
      return newArr
    },

    // 在编辑的时候切换题型
    tabQuestionsTypeFn() {
      if (!this.isEdit) return
      this.radioNum = ''
      this.checkboxNum = []
      this.options = []
      this.numBerTotal = 4
      this.numBerIndex = 0
      this.letterAdd()
    },

    // 判断是否是编辑
    async isEditFn() {
      if (this.$route?.query?.id || this.$route.query.id === 0) {
        this.isEdit = true
        const res = await detail({ id: this.$route.query.id })
        console.log(res.data)
        // 筛选出form里没有的
        const res2 = await directoryListSimple({ subjectID: res.data.subjectID })
        this.applyLists.directoryList = res2.data
        const res3 = await tagsListSimple({ subjectID: this.form.subjectID })
        this.applyLists.tagsList = res3.data
        for (const k in res.data) {
          if (this.form[k] === undefined) {
            this.isEditInfo[k] = res.data[k]
          }
        }

        for (const k in this.form) {
          if (k === 'tags') {
            if (res.data[k]) {
              this.form[k] = res.data[k].split(',')
            } else if (res.data[k] === '') {
              delete res.data[k]
            }
          } else if (k === 'questionType' || k === 'difficulty') {
            this.form[k] = Number(res.data[k])
          } else {
            this.form[k] = res.data[k]
          }
        }

        // 回显编辑器
        this.$refs.wangeditor.appendTxt(this.form.question)
        this.$refs.wangeditoranswer.appendTxt(this.form.answer)

        const OptionsSubsequenceList = this.getOptionsSubsequence(res.data.options)

        this.options = OptionsSubsequenceList.map(obj => {
          if (obj.isRight) {
            obj.isRight = true
          } else {
            obj.isRight = false
          }
          return obj
        })

        if (this.form.questionType === 1) {
          const index = this.options.findIndex(obj => obj.isRight === true)
          this.radioNum = index
        } else if (this.form.questionType === 2) {
          this.numBerTotal = res.data.options.length
          this.numBerIndex = res.data.options.length
          this.options.forEach((obj, index) => {
            if (obj.isRight === true) {
              this.checkboxNum.push(index)
            }
          })
        } else if (this.form.questionType === 3) {
          this.options = []
          this.letterAdd()
        }

        // res.data.
      }
    },

    // 点击确认提交
    addSunmitFn() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) return

        for (const k in this.form) {
          if (k === 'tags') {
            if (this.form[k] === [] || this.form[k] === '') {
              delete this.form[k]
            } else {
              this.form[k] = this.form[k].join(',')
            }
          } else if (k === 'questionType' || k === 'difficulty') {
            this.form[k] = String(this.form[k])
          }
        }

        // 如果是编辑
        if (this.isEdit) {
          const res = await update({ ...this.form, options: this.options, ...this.isEditInfo })

          if (res?.data.success) {
            this.$message.success('修改成功')
            this.$router.push('/questions/choice')
          }
          return
        }

        const res = await addQuestionsNew({ ...this.form, options: this.options })

        if (res?.data?.id || res.data.id === 0) {
          this.$message.success('成功添加题')
          this.$refs.form.resetFields()
          this.$refs.wangeditor.clearTxt()
          this.$refs.wangeditoranswer.clearTxt()
          this.form = {
            subjectID: '',
            catalogID: '',
            enterpriseID: '',
            province: '',
            city: '',
            direction: '',
            questionType: 1,
            difficulty: 1,
            question: '',
            videoURL: '',
            answer: '',
            remarks: '',
            tags: ''
          }

          this.numBerTotal = 4// 字母自定义循环四次
          this.numBerIndex = 0// 字母自定义循环第几次
          this.letterAdd()
          this.$router.push('/questions/list')
        } else {
          this.$message.success('请再试一次')
        }
      })
    },

    // 上传完图片
    imageUploadFn(url, index) {
      this.options[index].img = url
    },

    // 点击增加选项与答案
    addTabAnswerFn() {
      this.numBerIndex++
      this.options.push({
        code: `${String.fromCharCode('A'.charCodeAt(0) + this.numBerIndex)}`,
        title: '',
        img: '',
        isRight: false
      })
    },

    // 字母增减
    letterAdd() {
      for (let index = 0; index < this.numBerTotal; index++) {
        this.options.push({
          code: `${String.fromCharCode('A'.charCodeAt(0) + index)}`,
          title: '',
          img: '',
          isRight: false
        })
        this.numBerIndex = index
      }
    },

    async applyListsFn() {
      // 获取企业列表
      const res = await firm()
      this.applyLists.firmList = res.data.items
      // 获取学科列表
      const res2 = await subjectListSimple()
      this.applyLists.subjectList = res2.data
    },

    // 学科选择器change事件
    async subjectChangeFn() {
      this.form.catalogID = ''
      this.form.tags = ''
      const res = await directoryListSimple({ subjectID: this.form.subjectID })
      this.applyLists.directoryList = res.data
      const res2 = await tagsListSimple({ subjectID: this.form.subjectID })
      this.applyLists.tagsList = res2.data
    },

    // 城市选择器change事件
    provinceChangeFn() {
      this.form.city = ''
      this.applyLists.citysList = citys(this.form.province)
    }
  }
}
</script>

<style  scoped>
.porCol{
  position: relative;
  margin-bottom: 20px;
}
  .uploadImg{
    position: absolute;
    top: -10px;
    left: 310px;
    margin-bottom: 15px;
  }

.bottom {
  text-align: center;
}
</style>
<style scoped lang="scss">
.cityCol {
  margin-right: 19px;
}
.selectWidth {
  width: 400px;
}
.InputWidth {
  width: 400px;
}
.el-form-item.itemCity.is-required.el-form-item--medium {
    position: absolute;
    top: 270px;
    left: 250px;
}
.citySelect{
  width: 190px;
}
</style>
